﻿using System.Collections;
using UnityEngine;

public class RayCaster : ActionController
{
    private LayerMask groundLayer;
    private float distance_onGround = 0.8f;
    private Vector3 offset_rayCast = new Vector3(0.6f, 0);

    protected override void OnStart()
    {
        groundLayer = Service.Get<GameManager>().groundLayer;
        StartCoroutine(PhysicsCheck());
    }

    public IEnumerator PhysicsCheck()
    {
        for (; ; )
        {
            //待其他FixedUpdate执行玩再执行
            yield return new WaitForFixedUpdate();

            Vector3[] positions = new Vector3[]
            {
                transform_player.position + offset_rayCast,
                transform_player.position - offset_rayCast
            };

            player.distanceToGround = PhysicsTool.RaycastRanging(positions, Vector2.down, 100f, groundLayer);
            player.Grounded = player.distanceToGround < distance_onGround;
        }
    }

    private void OnDrawGizmos()
    {
        Vector3 pos0 = transform.position;
        Vector3 pos1 = pos0 + offset_rayCast;
        Vector3 pos2 = pos0 - offset_rayCast;
        Gizmos.color = Color.green;
        Gizmos.DrawLine(pos1, new Vector3(pos1.x, pos1.y - distance_onGround, 0));
        Gizmos.DrawLine(pos2, new Vector3(pos2.x, pos2.y - distance_onGround, 0));
    }
}
